package com.zlh.config;

import com.zlh.entity.QuartzEntity;
import com.zlh.service.JobService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @package com.zlh.config
 * @company: dacheng
 * @author: zlh
 * @createDate: 2022/6/14
 */
@Component
@Slf4j
public class TaskRunner implements ApplicationRunner {
    @Autowired
    private JobService jobService;
    @Autowired @Qualifier("Scheduler")
    private Scheduler scheduler;

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        /**
         * 系统启动的时候会初始化一个任务
         */
        Long count = jobService.listQuartzEntity(null);
        if(count==0){
            log.info("初始化测试任务,指明job的名称，所在组的名称，以及绑定job类");
            QuartzEntity quartz = new QuartzEntity();
            quartz.setJobName("jobName_test");
            quartz.setJobGroup("group_test");
            quartz.setTriggerName("trigger_test");
            quartz.setDescription("描述：测试任务");
            quartz.setJobClassName("com.zlh.job.ChickenJob");
            quartz.setCronExpression("*/5 * * * * ?");
            quartz.setJobMethodName("test1");
            Class cls = Class.forName(quartz.getJobClassName());
            cls.newInstance();
            //创建jobDetail实例，绑定Job实现类.构建job信息
            JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(quartz.getJobName(),
                    quartz.getJobGroup())
                    .withDescription(quartz.getDescription()).build();
            jobDetail.getJobDataMap().put("jobMethodName", "test1");
            // 定义调度触发规则,触发时间点，使用CronTrigger
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartz.getCronExpression());
            // 设置触发器
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(quartz.getTriggerName(), quartz.getJobGroup())
                    // 延迟1秒后执行
                    .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
                    .withSchedule(cronScheduleBuilder).build();
            // 把作业和触发器注册到任务调度中,交由Scheduler安排触发
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                // 调用start()方法后，Scheduler线程才开始启动触发器trigger，运行job
                scheduler.start();
            }
        }
    }
}
